﻿using System;
using System.Web.Mvc;
using System.Web.Routing;
using Castle.Windsor;

namespace Genesis.Infrastructure.Web.Factories
{

    public class WindsorControllerFactory : DefaultControllerFactory
    {

        private IWindsorContainer windsorContainer;

        public WindsorControllerFactory(IWindsorContainer windsorContainer)
        {

            this.windsorContainer = windsorContainer;

        }

        protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
        {

            try
            {

                return windsorContainer.Resolve(controllerType) as Controller;

            }
            catch
            {

                try
                {

                    return base.GetControllerInstance(requestContext, controllerType);

                }
                catch
                {

                    return null;

                }

            }

        }

        public override void ReleaseController(IController controller)
        {

            windsorContainer.Release(controller);

        }

    }

}